package com.accloud.cloudservice;

import com.accloud.service.ACObject;
import com.accloud.service.Comparison;
import com.accloud.service.Expression;
import com.accloud.service.QueryOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

class ScanQueryParameter extends DStoreQueryParameter {
    public static final int ORDER_ASC = 1;
    public static final int ORDER_DESC = 2;
    private ACObject scanParam = new ACObject();

    ScanQueryParameter(long deviceId, QueryOption queryOption) {
        super(1, 2);
        putKeys(this.scanParam, "id", Long.valueOf(deviceId));
        if (queryOption.getCriteria() != null) {
            ArrayList<Object> filters = new ArrayList<>();
            Iterator<Expression> it = queryOption.getCriteria().getExpressions().iterator();
            while (it.hasNext()) {
                Comparison comparison = (Comparison) it.next();
                ACObject comp = new ACObject();
                comp.put("key", comparison.key);
                comp.put("operator", Integer.valueOf(comparison.operator));
                comp.put("value", comparison.value);
                ArrayList<Object> value = new ArrayList<>();
                value.add(comp);
                ACObject item = new ACObject();
                item.put("connector", 1);
                item.put("filter", value);
                filters.add(item);
            }
            this.scanParam.put("filters", filters);
        }
        String[] projection = queryOption.getProjection();
        if (projection == null || projection.length <= 0) {
            this.scanParam.delete("select");
        } else {
            ArrayList<String> value2 = new ArrayList<>(Arrays.asList(projection));
            value2.add("timestamp");
            this.scanParam.put("select", value2);
        }
        if (queryOption.getStartTime() > 0) {
            this.scanParam.put("startKeys", new TimeKey(queryOption.getStartTime()));
        }
        if (queryOption.getEndTime() > 0) {
            this.scanParam.put("endKeys", new TimeKey(queryOption.getEndTime()));
        }
        ArrayList<Object> orders = new ArrayList<>();
        orders.add(new Order("timestamp", 2));
        this.scanParam.put("orderBy", orders);
        this.scanParam.put("limit", Integer.valueOf(queryOption.getLimit()));
        put("scanParam", this.scanParam);
    }

    static class TimeKey extends ACObject {
        private TimeKey(long timestamp) {
            put("_border", 1);
            put("timestamp", Long.valueOf(timestamp));
        }
    }

    static class Order extends ACObject {
        private Order(String key, int order) {
            put("key", key);
            put("order", Integer.valueOf(order));
        }
    }
}
